<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/3
 * Time: 17:12
 */
namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\token\driver\Redis;
use app\common\model\CommissionRebate;
use app\common\model\CouponCollectRecord;
use app\common\model\FundsRecord;
use think\Db;
use think\Exception;

class Jd extends Api {
	protected $noNeedRight = '*';
	
	public function search(){
		$obj = new \app\common\controller\Jd();
		$keyword = input('post.keyword');
		$page = input('post.page', 1, 'intval');
		$goods = $obj->search($page, $keyword);
		if($goods === false) {
			$this->error('服务器繁忙，请稍候重试');
		}
		
		$this->success('查询成功', $goods);
	}
	
	public function getGoods($keyword){
		$redis = new \Redis();
		if(!$redis->connect('127.0.0.1', 6379)){
			$this->error('redis连接出错');
		};
		
		$key = 'jd_goods_search_'.md5($keyword);
		$redis->auth(config('redis.password'));
		return $redis->get($key);
	}
	
	/**
	 * 京东推荐商品
	 */
	public function getRecommendGoods(){
		
		$obj = new \app\common\controller\Jd();
		$keyword = input('post.keyword');
		$page = input('post.page', 1, 'intval');
		$goods = $obj->search($page, $keyword);
		if($goods === false) {
			$this->error('服务器繁忙，请稍候重试');
		}
		
		$this->success('查询成功', $goods);
	}
	
	/**
	 * 兑换优惠 券
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function exchangeCoupon($data){
		Db::startTrans();
		try {
			//添加领取记录
			$couponModel = new CouponCollectRecord();
			$couponRes = $couponModel->isUpdate(false)->save([
				'user_id' => $this->auth->id,
				'type' => $couponModel::TYPE_JD,
				'goods_id' => $data['goods_id'],
			]);
			if(!$couponRes) {
				throw new Exception('添加领取记录出错');
			}
			
			$coupon_url = '';
			$jdObj = new \app\common\controller\Jd();
			//如果还没有生成优惠券领取信息，加入到生成优惠券队列
			if($data['coupon_amount'] > 0) {
				
				$couponStatus = $jdObj->createCouponUrl($data);
				if ($couponStatus) {
					$coupon_url = $couponStatus;
					$user = Db::name('user')->field('id, voucher_balance')->find($this->auth->id);
					if($user['voucher_balance'] < $data['coupon_amount']) {
						throw new Exception('优惠券不足,当前优惠券余额【'.$user['voucher_balance'].'】元');
					}
					
					//扣除优惠券
					$userRes = Db::name('user')
						->where(['id' => $user['id']])
						->setDec('voucher_balance', $data['coupon_amount']);
					if(!$userRes) {
						throw new Exception('扣除优惠券出错');
					}
					
					//记录资金记录
					$logModel = new FundsRecord();
					$logRes = $logModel->addRecord($user['id'], $data['coupon_amount'], $user['voucher_balance'], $logModel::ACCOUNT_TYPE_VOUCHER, $logModel::OPE_TYPE_LESS, $logModel::TYPE_VOUCHER_JD);
					if(!$logRes) {
						throw new Exception('添加资金记录出错');
					}
				}
				
				
			}
			
			//生成带用户信息的推广信息链接
			
			$res = $jdObj->promotionCommonGet($data['item_url'], $this->auth->id);
			if(!$res) {
				throw new Exception('生成推广链接出错');
			}
			
			Db::commit();
			return [
				'status' => true,
				'info' => [
					'coupon_url' => $coupon_url,
					'goods_url' => $res['clickURL']
				]
			];
			
		} catch (Exception $e) {
			Db::rollback();
			return [
				'status' => false,
				'info' => $e->getMessage()
			];
		}
		
	}
	
	
	protected function getCouponUrl($goodsId){
		$redis = new \Redis();
		if(!$redis->connect('127.0.0.1', 6379)){
			$this->error('redis连接出错');
		};
		
		$key = 'jd_goods_coupon_url_'.md5($goodsId);
		$redis->auth(config('redis.password'));
		return $redis->get($key);
	}
	
	public function test(){
		$js = new \app\common\controller\Jd();
		
		//订单查询
		$res = $js->orderQuery();
		
//		$res = $js->promotionCommonGet();
		
		$this->success('aa', $res);
	}
}